package com.example.com.skills_utf8;

import android.content.Intent;
import android.os.AsyncTask;
import android.util.Base64;
import android.view.View;
import android.widget.Button;

import com.app.BaseFragment;
import com.app.net.NetHelper;
import com.app.util.Utils_Log;
import com.utils.GsonParse;
import com.utils.g;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by matengfei on 15/7/27.
 */
public class _62RegisterVoiceFragment extends BaseFragment{


    Button btn_play;
    Button btn_record;
    Button btn_stop_record;
    Button btn_submit;

    String filename_audio = "";


    @Override
    public Integer InitLayout() {
        return R.layout.fragment__62_register_voice;
    }

    @Override
    public void InitView(View view) {

        btn_record = (Button)view.findViewById(R.id.btn_record);
        btn_stop_record = (Button)view.findViewById(R.id.btn_stop_record);
        btn_play = (Button)view.findViewById(R.id.btn_play);
        btn_submit = (Button)view.findViewById(R.id.btn_submit);


        Intent intent = new Intent(activity, _62IsvDemo.class);
        startActivity(intent);

    }

    @Override
    public void InitListener() {

        btn_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                String filename = "1.pcm";
                filename_audio= ApplicationCustom.getInstance().audio.init(filename);
                ApplicationCustom.getInstance().audio.start_record();

            }
        });
        btn_stop_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                filename_audio = ApplicationCustom.getInstance().audio.close_record();


            }
        });

        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ApplicationCustom.getInstance().audio.play();

            }
        });

        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                do_voice();
            }
        });

    }

    @Override
    public void InitProcess() {



    }



    void do_voice(){

        if(filename_audio.isEmpty()){

        }
        else {
            //requestNetData_uploadaudio(filename_audio);


            requestNetData_token();


        }

    }


    void requestNetData_uploadaudio(final String token){



        new NetHelper(getActivity()){

            @Override
            public String init(ArrayList<BasicNameValuePair> map) {

                /*
                format 	sting 	必填 	语音压缩的格式，请填写上述格式之一，不区分大小写
                rate 	int 	必填 	采样率，支持 8000 或者 16000
                channel 	int 	必填 	声道数，仅支持单声道，请填写 1
                cuid 	string 	必填 	用户 ID，推荐使用设备mac 地址/手机IMEI 等设备唯一性参数
                token 	string 	必填 	开发者身份验证密钥
                */

                byte[] raw = ApplicationCustom.getInstance().audio.getContent();
                int speech_length = raw.length;
                String speech = new String( Base64.encode(raw, Base64.DEFAULT) );

                map.add( new BasicNameValuePair("format", "pcm"));
                map.add( new BasicNameValuePair("rate", "8000"));
                map.add( new BasicNameValuePair("channel", "1"));
                map.add( new BasicNameValuePair("token", token));
                map.add( new BasicNameValuePair("cuid", g.id_umeng));

                map.add( new BasicNameValuePair("len", ""+speech_length));
                map.add( new BasicNameValuePair("speech", speech));

                return "http://vop.baidu.com/server_api";
                //return g.SERVER_PAY_HOST + g.SERVER_PAY_API.updateaudio;
            }

            @Override
            public void onComplete(String message) throws JSONException {
                JSONObject obj = new JSONObject(message);


            }
        }.start_volley_POST();

    }

    ///*
    private void raw_post(final String token) {


        new AsyncTask<Void, Void, Void>(){


            @Override
            protected Void doInBackground(Void... params) {

                try {

                    String url = "http://vop.baidu.com/server_api";
                    Map<String, Object> map = new HashMap<String, Object>() ;

                    byte[] raw = ApplicationCustom.getInstance().audio.getContent();
                    int speech_length = raw.length;
                    String speech = new String( Base64.encode(raw, Base64.DEFAULT) );

                    map.put("format", "pcm");
                    map.put("rate", 8000);
                    map.put("channel", 1);
                    map.put("token", token);
                    map.put("cuid", g.id_umeng);

                    map.put("len", speech_length);
                    map.put("speech", speech);

                    HttpPost request = new HttpPost(url);
                    String str_request = map.toString();

                    StringEntity se = new StringEntity(str_request, HTTP.UTF_8);
                    request.setEntity(se);

                    // 发送请求
                    request.addHeader("Content-Type", "application/json");
           //         request.addHeader("Content-length", ""+se.getContentLength());

                    HttpResponse httpResponse = new DefaultHttpClient()
                            .execute(request);
                    // 得到应答的字符串，这也是一个 JSON 格式保存的数据
                    String strNetRespone = EntityUtils.toString(
                            httpResponse.getEntity(), "utf-8");
                    Utils_Log.e(TAG, "" + strNetRespone);



                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();

                }

                return null;
            }


        }.execute(null, null, null);



    }
    //*/


    void requestNetData_token(){
        new NetHelper(getActivity()){

            @Override
            public String init(ArrayList<BasicNameValuePair> map) {

                map.add(new BasicNameValuePair("grant_type", "client_credentials"));
                map.add(new BasicNameValuePair("client_id", "5EqtoxgRxYcD63YrGF2dVX7L"));
                map.add(new BasicNameValuePair("client_secret", "rbxD33YXyQbWRYxGUdzImG3G3xjQKrmj"));
                return "https://openapi.baidu.com/oauth/2.0/token";
            }

            @Override
            public void onComplete(String message) throws JSONException {

                    Bean bean = (Bean) GsonParse.parse(message, Bean.class);
                    if(bean != null){
                        //requestNetData_uploadaudio(bean.getAccess_token());
                        raw_post( bean.getAccess_token() );
                    }

            }
        }.start_GET();
    }




    class Bean{

        /**
         * scope : public audio_voice_assistant_get wise_adapt lebo_resource_base lightservice_public hetu_basic
         * session_secret : d58c10a31ac5bc40e4486982107025a8
         * expires_in : 2592000
         * refresh_token : 25.8de0988e6a998cdf71b81d0f1064410f.315360000.1753333501.282335-3327401
         * session_key : 9mzdWWLELFuKmjiB9oCf1K3F7eEy4qOoUV25x1RyU9U6NL4oi1baNZeEo01Z5+gbj5rTh55cIRSOXiwRVTgW0QRtOeNc
         * access_token : 24.b8d1267a8363ace2c469b36dabddd355.2592000.1440565501.282335-3327401
         */
        private String scope;
        private String session_secret;
        private int expires_in;
        private String refresh_token;
        private String session_key;
        private String access_token;

        public void setScope(String scope) {
            this.scope = scope;
        }

        public void setSession_secret(String session_secret) {
            this.session_secret = session_secret;
        }

        public void setExpires_in(int expires_in) {
            this.expires_in = expires_in;
        }

        public void setRefresh_token(String refresh_token) {
            this.refresh_token = refresh_token;
        }

        public void setSession_key(String session_key) {
            this.session_key = session_key;
        }

        public void setAccess_token(String access_token) {
            this.access_token = access_token;
        }

        public String getScope() {
            return scope;
        }

        public String getSession_secret() {
            return session_secret;
        }

        public int getExpires_in() {
            return expires_in;
        }

        public String getRefresh_token() {
            return refresh_token;
        }

        public String getSession_key() {
            return session_key;
        }

        public String getAccess_token() {
            return access_token;
        }
    }






}
